const compileUtil = {
  getVal(expr, vm) {
    // [person, name]
    return expr.split('.').reduce((data, currentVal) => {
      return data[currentVal]
    }, vm.$data)
  },
  setVal(expr, vm, inputVal) {
    let data = vm.$data;
    let arr = expr.split('.');
    arr.reduce((data, currentVal, index) => {
      if (index === arr.length - 1) {
        data[currentVal] = inputVal;
      }
      return data[currentVal]
    }, data)
  },
  getContentVal(expr, vm) {
    return expr.replace(/\{\{(.+?)\}\}/g, (...args) => {
      return this.getVal(args[1], vm)
    })
  },
  text(node, expr, vm) {
    let value;
    if (expr.indexOf('{{') !== -1) {
      value = expr.replace(/\{\{(.+?)\}\}/g, (...args) => {
        new Watcher(vm, args[1], (val) => {
          this.updater.textUpdater(node, this.getContentVal(expr, vm));
        })
        return this.getVal(args[1], vm)
      })
    } else {
      value = this.getVal(expr, vm);
    }

    this.updater.textUpdater(node, value);
  },
  html(node, expr, vm) {
    const value = this.getVal(expr, vm);
    new Watcher(vm, expr, (val) => {
      this.updater.htmlUpdater(node, val);
    })
    this.updater.htmlUpdater(node, value);
  },
  model(node, expr, vm) {
    const value = this.getVal(expr, vm);
    // 监听数据变化
    new Watcher(vm, expr, (val) => {
      this.updater.modelUpdater(node, val);
    })
    // v-modal双向绑定
    node.addEventListener('input', (e) => {
      this.setVal(expr, vm, e.target.value);
    })
    this.updater.modelUpdater(node, value);
  },
  on(node, expr, vm, eventName) {
    let fn = vm.$options.methods && vm.$options.methods[expr];
    node.addEventListener(eventName, fn.bind(vm), false);
  },
  bind(node, expr, vm, attrName) {
    const value = this.getVal(expr, vm);
    new Watcher(vm, expr, (val) => {
      this.updater.bindUpdater(node, val, attrName);
    })
    this.updater.bindUpdater(node, value, attrName);
  },
  // 更新函数
  updater: {
    textUpdater(node, value) {
      node.textContent = value;
    },
    htmlUpdater(node, value) {
      node.innerHTML = value;
    },
    modelUpdater(node, value) {
      node.value = value;
    },
    bindUpdater(node, value, attrName) {
      node.setAttribute(attrName, value);
    }
  }
}
class Compile {
  constructor(el, vm) {
    this.el = this.isElementNode(el) ? el : document.querySelector(el);
    this.vm = vm;
    // 1. 获取文档碎片对象 放如内存中减少页面的回流和重绘
    const fragment = this.node2Fragment(this.el);
    // 2. 编译模板
    this.compile(fragment);
    // 3. 将文档碎片对象放回页面
    this.el.appendChild(fragment)
  }
  compile(fragment) {
    // 1. 获取子节点
    const childNodes = fragment.childNodes;
    [...childNodes].forEach(child => {
      if (this.isElementNode(child)) {
        // 是元素节点
        // 编译元素节点
        this.compileElement(child)
        if (child.childNodes.length > 0) {
          this.compile(child)
        }
      } else {
        // 是文本节点
        // 编译文本节点
        this.compileText(child)
      }
    })
  }
  compileElement(node) {
    // <div v-text="msg"></div>
    const attributes = node.attributes;
    [...attributes].forEach(attr => {
      const { name, value } = attr;
      if (this.isDirective(name)) {
        const [, directive] = name.split('-');
        const [dirName, eventName] = directive.split(':');
        // v-model v-text v-on:click
        compileUtil[dirName](node, value, this.vm, eventName)
        // 移除指令属性
        node.removeAttribute('v-' + directive)
      } else if (this.isEventName(name)) {
        let [, eventName] = name.split('@');
        compileUtil['on'](node, value, this.vm, eventName)
      }
    })
  }
  compileText(node) {
    const content = node.textContent;
    if (/\{\{(.+?)\}\}/.test(content)) {
      compileUtil['text'](node, content, this.vm)
    }
  }
  isEventName(attrName) {
    return attrName.startsWith('@')
  }
  isDirective(attrName) {
    return attrName.startsWith('v-')
  }
  node2Fragment(node) {
    const f = document.createDocumentFragment();
    let firstChild;
    while (firstChild = node.firstChild) {
      f.appendChild(firstChild)
    }
    return f;
  }
  isElementNode(node) {
    return node.nodeType === 1
  }
}

class MVue {
  constructor(options) {
    this.$el = options.el
    this.$data = options.data
    this.$options = options;
    if (this.$el) {
      // 1. 实现一个数据观察者
      new Observer(this.$data)
      // 2. 实现一个指令解析器
      new Compile(this.$el, this)
      // 3. 实现一个数据劫持
      this.proxyData(this.$data)
    }
  }
  proxyData(data) {
    Object.keys(data).forEach(key => {
      Object.defineProperty(this, key, {
        get() {
          return data[key]
        },
        set(newValue) {
          data[key] = newValue
        }
      })
    })
  }
}